package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.GenerateOrders;
import com.zhiqianbao.entity.PayOrderList;
import com.zhiqianbao.entity.Repay;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.Third;
import com.zhiqianbao.pay.utils.BaseHelper;
import com.zhiqianbao.pay.utils.EnvConstants;
import com.zhiqianbao.pay.utils.MobileSecurePayer;
import com.zhiqianbao.pay.utils.PayOrder;
import com.zhiqianbao.pay.utils.Rsa;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.SignConfigUtils;
import com.zhiqianbao.utils.SystemUtils;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.utils.WorthPurseUtil;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/14.
 */
public class RepayVerifyActivity extends BaseActivity implements View.OnClickListener{
    public static final int DATA_FAILED=0x123;
    public static final int LOCKINNG=0x124;
    public static final int PREPAY=0x125;
    public static final int PAYMENT=0x126;
    private Gson gson = new Gson();
    /**
     * 在线支付按钮
     */
    Button onlinePay;
    /**
     * 银行卡/支付宝转账按钮
     */
    Button offlinePay;
    private AlertDialog myDialog = null;
    WebView mWebView;
    /**
     * 当期借款
     */
    Repay repay;
    private  Button radiobutton_lianlian;
    String couponId="";
    String couponType="";
    private  Result<Void> data;
    //选择支付宝
    private  int position;
    private Button radiobutton_zhifubao;
    private Button radiobitton_rongbao;
    private int pay_type_flag = 1;
    private boolean boo_display_pwd = true;
    private boolean boo_display_pwd1 = true;
    private boolean boo_display_pwd3 = true;
    private LinearLayout layout_radiogroup;
    private  LinearLayout radiogroup;
    SharedPreferanceUtils sharedPreferanceUtils;
    private String endTime;
    private String startTime;
    PayOrder order = null;
    private  String lianlianPayStatus;
    private String aliPayStatus;
    private String rongbaoPayStatus;
    private String busi_partner;
    private String no_order;
    private  String dt_order;
    private String name_goods;
    private  String sign_type;
    private  String notify_url;
    private  String valid_order;
    private String shareing_data;
    private  String money_order;
    private String id_no;
    private String oid_partner;
    private  String acct_name;
    private  String no_agree;
    private String user_id;
    private   String total_fee;
    private String term;
    private String cash_fee;
    private Bundle bundle_pay;
    private String sign1;
    private String user_info_bind_phone;
    private String user_info_dt_register ;
    private String user_info_full_name ;
    private String user_info_id_no ;
    private String user_info_identify_state ;
    private String user_info_identify_type ;
    private String user_info_mercht_userlogin ;
    private String user_info_mercht_userno;
    private String sign11;
    private String info_order;
    private String retCode;
    private String card_no;
    private  AlertDialog prepayDialog;
    private String startTimes="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repay_verify);
        init();
        initView();
        initData();
    }


    private void initData() {
        try{
            lianlianPayStatus = sharedPreferanceUtils.getLianlianPayStatus();
            aliPayStatus = sharedPreferanceUtils.getAliPayStatus();
            rongbaoPayStatus = sharedPreferanceUtils.getRongbaoPayStatus();
        }catch (Exception e){

        }

        //还款页面添加时间统计
        startTimes=TimeStatisticsUtil.getTime();

    }

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");

                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
//                            // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                               //连连(认证支付)前端判断请求成功锁定订单接口
                                showShortToast1(retMsg);
                                getPayResult();
                        } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                            showShortToast1(retMsg);
                        } else {
                            showShortToast1(retMsg);
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            };
        };

    }

    private void getPayResult() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("orderNo",no_order);
                mapParams.put("retCode",retCode);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/lianlian/authpay/locking",
                        mapParams, RepayVerifyActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILED;
                } else {
                    message.what = LOCKINNG;
                    Third data =gson.fromJson(result, Third.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }


    private void initView() {
         onlinePay=(Button)findViewById(R.id.online_pay);
         offlinePay=(Button)findViewById(R.id.offline_pay);
         mWebView=(WebView)findViewById(R.id.mWebView);
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        myDialog = new AlertDialog.Builder(this,R.style.Dialog).create();
        Intent intent = getIntent();
        repay = (Repay) intent.getSerializableExtra("repay");
        couponId=intent.getStringExtra("couponId");
        Log.i("优惠券id.12122",couponId);
        couponType=intent.getStringExtra("couponType");
        WebSettings webSettings = mWebView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        CookieManager.getInstance().setAcceptCookie(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(false);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //加载需要显示的网页
        mWebView.loadUrl(Constants.API_ROOT + "/webview/getLoanInfoOfRepay?userId="
                + Constants.LOGIN_USER.getId() + "&terms=" + repay.getTerms()
                +"&couponId="+couponId+"&couponType="+couponType
                + "&loanId=" + repay.getLoanId() + "&token=" + Constants.LOGIN_USER.getToken());
        //设置Web视图
        mWebView.setWebViewClient(new WebViewClient());

        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });

        mWebView.addJavascriptInterface(this, "applyInfo");

        onlinePay.setOnClickListener(this);
        offlinePay.setOnClickListener(this);

        if(!TextUtils.isEmpty(couponId)) {
            offlinePay.setTextColor(Color.GRAY);
            offlinePay.setBackgroundResource(R.drawable.i_img_apply_cancel_request_normal_icon);
        }
        else{
            offlinePay.setTextColor(Color.parseColor("#FFC7412D"));
            offlinePay.setBackgroundResource(R.drawable.i_img_apply_cancel_request_pressed_icon);
        }
    }

    @Override
    public void onClick(View v) {
        if(R.id.online_pay==v.getId()) {
            setPayDialog();
        }
        else if(R.id.offline_pay==v.getId()){
                if(!TextUtils.isEmpty(couponId)) {
                    showShortToast1("抱歉，使用优惠券只支持线上还款！");
                }
                else {
                    Intent offlinePayIntent = new Intent(this, RepayOfflineSelectActivity.class);
                    offlinePayIntent.putExtra("repay", repay);
                    startActivity(offlinePayIntent);
                }
        }
    }


    private void setPayDialog() {
        myDialog.show();
        Window window = myDialog.getWindow();
        window.setContentView(R.layout.pay_dialogs);
       ImageView iv_close = (ImageView) window.findViewById(R.id.iv_close);
        radiogroup = (LinearLayout)window.findViewById(R.id.radiogroup);
        layout_radiogroup = (LinearLayout) window.findViewById(R.id.layout_radiogroup);
        radiobutton_lianlian = (Button)window.findViewById(R.id.radiobutton_lianlian);
        radiobutton_zhifubao = (Button)window.findViewById(R.id.radiobutton_zhifubao);
        radiobitton_rongbao =  (Button)window.findViewById(R.id.radiobitton_rongbao);
        final LinearLayout  ll_raditon = (LinearLayout)window.findViewById(R.id.ll_raditon);
        Button bt_payButton =  (Button) window.findViewById(R.id.bt_payButton);
        position = 2;
        if (!TextUtils.isEmpty(lianlianPayStatus) && lianlianPayStatus.equals("1")){

            radiogroup.setVisibility(View.VISIBLE);
            radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_on);
        }else {
            radiogroup.setBackgroundColor(getResources().getColor(R.color.gray));
            radiobutton_lianlian.setEnabled(false);
            if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(lianlianPayStatus)){
                if (lianlianPayStatus.equals("0")&&rongbaoPayStatus.equals("0")){

                }else {
                    radiobutton_zhifubao.setBackgroundResource(R.drawable.dx_checkbox_on);
                }
            }


            position = 3;
        }
        //连联和支付宝
        if (!TextUtils.isEmpty(lianlianPayStatus)&&!TextUtils.isEmpty(aliPayStatus)){
            if (lianlianPayStatus.equals("0")&&aliPayStatus.equals("0")){
                radiobutton_lianlian.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_lianlian.setEnabled(false);
                radiobutton_zhifubao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_zhifubao.setEnabled(false);
                radiobitton_rongbao.setBackgroundResource(R.drawable.dx_checkbox_on);
                position = 1;
            }
        }

        //支付宝和荣宝
        if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(aliPayStatus)){
            if (rongbaoPayStatus.equals("0")&&aliPayStatus.equals("0")){
                radiobitton_rongbao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobitton_rongbao.setEnabled(false);
                radiobutton_zhifubao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_zhifubao.setEnabled(false);
                radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_on);
                position = 2;
            }
        }
        //连连和荣宝
        if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(lianlianPayStatus)){
            if (lianlianPayStatus.equals("0")&&rongbaoPayStatus.equals("0")){
                radiobutton_lianlian.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_lianlian.setEnabled(false);
                radiobitton_rongbao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobitton_rongbao.setEnabled(false);
                radiobutton_zhifubao.setBackgroundResource(R.drawable.dx_checkbox_on);
                position = 3;
            }
        }

        //三种支付全部
        if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(lianlianPayStatus)&&!TextUtils.isEmpty(aliPayStatus)){
            if (lianlianPayStatus.equals("0")&&rongbaoPayStatus.equals("0")&&aliPayStatus.equals("0")){
                radiobutton_lianlian.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_lianlian.setEnabled(false);
                radiobitton_rongbao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobitton_rongbao.setEnabled(false);
                radiobutton_zhifubao.setBackgroundColor(getResources().getColor(R.color.gray));
                radiobutton_lianlian.setEnabled(false);

            }
        }

        if (!TextUtils.isEmpty(aliPayStatus) && aliPayStatus.equals("1")){

            layout_radiogroup.setVisibility(View.VISIBLE);
        }else {
            layout_radiogroup.setBackgroundColor(getResources().getColor(R.color.gray));
            radiobutton_zhifubao.setEnabled(false);

//            radiobitton_rongbao.setBackgroundResource(R.drawable.dx_checkbox_on);
            if (!TextUtils.isEmpty(lianlianPayStatus)&&!TextUtils.isEmpty(aliPayStatus)){
                if (lianlianPayStatus.equals("0")&&aliPayStatus.equals("0")){
                    position = 1;
                }else {
                    position = 2;
                }
            }

        }
        if (!TextUtils.isEmpty(rongbaoPayStatus) && rongbaoPayStatus.equals("1")){
            ll_raditon.setVisibility(View.VISIBLE);
        }else {
            ll_raditon.setBackgroundColor(getResources().getColor(R.color.gray));
            radiobitton_rongbao.setEnabled(false);
            if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(lianlianPayStatus)){
                if (lianlianPayStatus.equals("0")&&rongbaoPayStatus.equals("0")) {
                    position = 3;
                }else {
                    radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_on);
                    position = 2;
                }
            }


        }
        bt_payButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(rongbaoPayStatus)&&!TextUtils.isEmpty(lianlianPayStatus)&&!TextUtils.isEmpty(aliPayStatus)){
                    if (lianlianPayStatus.equals("0")&&rongbaoPayStatus.equals("0")&&aliPayStatus.equals("0")){
                        showShortToast1("在线还款暂无还款渠道,请耐心等待!");

                    }else {
                        if (position == 1){
                            Map<String, String> systemInfo = SystemUtils.getSystemInfo(RepayVerifyActivity.this);
                            String imei="";
                            if(systemInfo!=null) {
                                imei = systemInfo.get("imei");
                            }
                            //融宝
                            //判断本期是否已经还款成功
                            Map<String, String> params = new HashMap<>();
                            long timeStamp = System.currentTimeMillis();
                            //添加时间统计
                            String applyEndTime = TimeStatisticsUtil.getTime();
                            String applyStartTime = startTimes;
                            params.put("title", "米米贷借贷还款");
                            params.put("body", "偿还借款第" + repay.getTerms() + "期");
                            //params.put("totalFee", repay.getRepayTotal().toString());
                            params.put("totalFee", repay.getRepayTotal() + "");
                            params.put("userId", Constants.LOGIN_USER.getId() + "");
                            params.put("orderNo", repay.getId() + "");
                            params.put("startTime", applyStartTime);
                            params.put("endTime", applyEndTime);
                            params.put("imei", imei==null?"":imei);
                            params.put("token", Constants.LOGIN_USER.getToken());
                            params.put("couponId", couponId);
                            params.put("timestamp",String.valueOf(timeStamp));
                            String sign= SignConfigUtils.getSignParams(params);
                            params.put("sign",sign);
                            Intent rbPayIntent = new Intent(RepayVerifyActivity.this, RepayConfirmRbActivity.class);
                            rbPayIntent.putExtra("params", gson.toJson(params));
                            startActivity(rbPayIntent);
                            RepayVerifyActivity.this.finish();

                        }else if (position == 2){
                            //连连代扣
                            lianlianPaymentNew();
                        }else if (position == 3){
                            expressCouponDialog();

                        }
                    }
                }

            }
        });


        radiobitton_rongbao.setOnClickListener(new View.OnClickListener(){
//
            @Override
            public void onClick(View v) {
                 position = 1;

                radiobitton_rongbao.setBackgroundResource(R.drawable.dx_checkbox_on);
                radiobutton_zhifubao.setBackgroundResource(R.drawable.dx_checkbox_off);
                radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_off);
            }
//
        });

        radiobutton_lianlian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                position = 2;
                radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_on);
                radiobitton_rongbao.setBackgroundResource(R.drawable.dx_checkbox_off);
                radiobutton_zhifubao.setBackgroundResource(R.drawable.dx_checkbox_off);
            }
        });
        radiobutton_zhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                position = 3;
                radiobutton_zhifubao.setBackgroundResource(R.drawable.dx_checkbox_on);
                radiobitton_rongbao.setBackgroundResource(R.drawable.dx_checkbox_off);
                radiobutton_lianlian.setBackgroundResource(R.drawable.dx_checkbox_off);

            }
        });


        iv_close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                myDialog.dismiss();
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(RepayVerifyActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }

        });


    }

    private void expressCouponDialog() {
        myDialog.dismiss();
        prepayDialog  = new AlertDialog.Builder(RepayVerifyActivity.this, R.style.Dialog).create();
        prepayDialog.show();
        View view = LayoutInflater.from(RepayVerifyActivity.this).inflate(R.layout.dialog_zhifubao_pay, null);
        prepayDialog.getWindow().setContentView(view);
        prepayDialog.setCanceledOnTouchOutside(false);
        TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
        Button button = (Button) view.findViewById(R.id.positiveButton);
        Button cacelButton = (Button) view.findViewById(R.id.cacelButton);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        Map<String, String> mapParams = new HashMap<>();
                        mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                        mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                        mapParams.put("repayId",repay.getId() == null ? "" : repay.getId().toString());
                        mapParams.put("couponId",couponId);
                        mapParams.put("startTime",startTime);
                        mapParams.put("endTime",endTime);
                        mapParams.put("couponType",couponType);
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/payment/alipay/prepay",
                                mapParams, RepayVerifyActivity.this);
                        if (StringUtils.isBlank(result)) {
                            message.what = DATA_FAILED;
                        } else {
                            message.what = PREPAY;
                            GenerateOrders data =gson.fromJson(result, GenerateOrders.class);
                            message.obj = data;
                        }
                        postHandler.sendMessage(message);
                    }
                }).start();

            }
        });

        cacelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                prepayDialog.dismiss();
            }
        });
    }

    public boolean isMobile_spExist() {
        PackageManager manager = this.getPackageManager();
        List<PackageInfo> pkgList = manager.getInstalledPackages(0);
        for (int i = 0; i < pkgList.size(); i++) {
            PackageInfo pI = pkgList.get(i);
            if (pI.packageName.equalsIgnoreCase("com.eg.android.AlipayGphone"))
                return true;
        }
        return false;
    }


        //最新连连
    private void lianlianPaymentNew() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("repayId",repay.getId() == null ? "" : repay.getId().toString());
                mapParams.put("couponId",couponId == null ? "" : couponId);
                mapParams.put("couponType",couponType == null ? "" : couponType);
                mapParams.put("startTime",startTime);
                mapParams.put("endTime",endTime);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/lianlian/authpay/payment",
                        mapParams, RepayVerifyActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILED;
                } else {
                    message.what = PAYMENT;
                    PayOrderList data =gson.fromJson(result, PayOrderList.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    private void toH5Pay(String prepayId,String jumpUrl){

        String alipayWapJsStr = getFromAssets("alipaywap.js");

        String doApiStr = " function doApi(){alipay_wap('" + prepayId + "','" + jumpUrl + "');}; ";
        String onBtnClickStr = " function onBtnClick(){doApi()}; ";
        String doClickBtnStr = " function doClickBtn(){var vBtn = document.getElementById('btn'); vBtn.click();}; ";
        String onLoadStr = " window.onload = function () { }; ";
        String htmlStr = "<html><head><script type=\"text/javascript\">" + alipayWapJsStr + onLoadStr + doApiStr + onBtnClickStr + doClickBtnStr + "</script></head><body><button id='btn' onclick='onBtnClick()' style='width:100%;height:100%;background:#454545;color:#ffffff'>支付</button></body></html>";
        mWebView.loadDataWithBaseURL("http://localhost/", htmlStr, "text/html", "utf-8", null);
    }


    public String getFromAssets(String fileName){
        String result="";
        try {
            InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            while((line = bufReader.readLine()) != null)
                result += line;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private void lianlianPay() {
        myDialog.dismiss();
//        order = constructPreCardPayOrder();
        // 手势码+短信验证方式
        order = constructGesturePayOrder();
        // order.setShareing_data(((TextView)
        // findViewById(R.id.share_money)).getText()
        // .toString().trim());
        String content4Pay = BaseHelper.toJSONString(order);
        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持

        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.payAuth(content4Pay, mHandler,
                Constants.RQF_PAY, RepayVerifyActivity.this, false);
        // order.setShareing_data(((TextView)
        // findViewById(R.id.share_money)).getText()
        // .toString().trim());
//        String content4Pay = BaseHelper.toJSONString(order);
        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持

//        MobileSecurePayer msp = new MobileSecurePayer();
//        boolean bRet = msp.payAuth(content4Pay, mHandler,
//                Constants.RQF_PAY, RepayVerifyActivity.this, false);
    }

    private PayOrder constructGesturePayOrder() {
//        SimpleDateFormat dataFormat = new SimpleDateFormat(
//                "yyyyMMddHHmmss");
//        Date date = new Date();
//        String timeString = dataFormat.format(date);

        PayOrder order = new PayOrder();
        order.setBusi_partner(busi_partner);
        order.setNo_order(no_order);
        order.setDt_order(dt_order);
        order.setName_goods(name_goods);
        order.setNotify_url(notify_url);
        order.setCard_no(card_no);
        // MD5 签名方式
//        order.setSign_type(PayOrder.SIGN_TYPE_MD5);
        // RSA 签名方式
        order.setSign_type(sign_type);
        order.setValid_order(valid_order);

        order.setUser_id(user_id);
        order.setId_no(id_no);
        order.setAcct_name(acct_name);
        order.setMoney_order(money_order);
        order.setInfo_order(info_order);
        // 风险控制参数
        order.setRisk_item(constructRiskItem());

//        order.setFlag_modify("1");
        String sign = "";
        order.setOid_partner(oid_partner);
        String content = BaseHelper.sortParam(order);
        // MD5 签名方式, 签名方式包括两种，一种是MD5，一种是RSA 这个在商户站管理里有对验签方式和签名Key的配置。
//        sign = Md5Algorithm.getInstance().sign(content,
//                EnvConstants.MD5_KEY);
        // RSA 签名方式
        sign = Rsa.sign(content, EnvConstants.RSA_PRIVATE);
        order.setSign(sign);
        return order;
    }

    private PayOrder constructPreCardPayOrder() {

        PayOrder order = new PayOrder();
        order.setBusi_partner(busi_partner);
        order.setNo_order(no_order);
        order.setDt_order(dt_order);
        order.setName_goods(name_goods);
        order.setNotify_url(notify_url);
        order.setMoney_order(money_order);
        order.setId_no(id_no);
//        order.setOid_partner(oid_partner);
//        order.setDt_order(dt_order);
        order.setAcct_name(acct_name);
//        order.setBusi_partner(busi_partner);
//        order.setNo_agree(no_agree);
//        order.setUser_id(user_id);
        // MD5 签名方式
//        order.setSign_type(sign_type);
        // RSA 签名方式
         order.setSign_type(sign_type);
        String content = BaseHelper.sortParam(order);


        order.setValid_order(valid_order);

            // 银行卡卡号，该卡首次支付时必填
//            order.setCard_no(card_no);
            order.setId_no(id_no);


        // 风险控制参数
        order.setRisk_item(constructRiskItem());
//

        order.setOid_partner(oid_partner);
         content = BaseHelper.sortParam(order);
        // MD5 签名方式
//        sign = Md5Algorithm.getInstance().sign(content,
//                EnvConstants.MD5_KEY);
        // RSA 签名方式
//         sign = Rsa.sign(content,sign1);
//        order.setSign(sign);
         String sign = Rsa.sign(content, EnvConstants.RSA_PRIVATE);
        order.setSign(sign);
        return order;
    }

    private String constructRiskItem() {
        JSONObject mRiskItem = new JSONObject();
        try {
            mRiskItem.put("user_info_bind_phone",user_info_bind_phone);
            mRiskItem.put("user_info_dt_register",user_info_dt_register);
            mRiskItem.put("user_info_full_name",user_info_full_name);
            mRiskItem.put("user_info_id_no", user_info_id_no);
            mRiskItem.put("user_info_identify_state",user_info_identify_state);
            mRiskItem.put("user_info_identify_type",user_info_identify_type);
            mRiskItem.put("user_info_mercht_userlogin",user_info_mercht_userlogin);
            mRiskItem.put("user_info_mercht_userno",user_info_mercht_userno);

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (org.json.JSONException e) {
            e.printStackTrace();
        }
        return mRiskItem.toString();
    }



    private void lianlianPayment(){
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                params.put("userId",Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("repayId", repay.getId() == null ? "" : repay.getId().toString());

                //添加时间统计
                String endTime= TimeStatisticsUtil.getTime();
                String startTime=startTimes;
                params.put("startTime", startTime);
                params.put("endTime", endTime);
                //新添还款添加优惠券
                if(!TextUtils.isEmpty(couponId)) {
                    params.put("couponId", couponId);
                    params.put("couponType",couponType);
                }
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/lianlian/paymentNew", params,RepayVerifyActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<Void> data = Result.fromJson(result, Void.class);
                    message.obj = data;
                }
                lianlianPaymentHander.sendMessage(message);
            }
        }).start();
    }

    private Handler lianlianPaymentHander = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            closeWaitDialog();
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    data = (Result<Void>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            showShortToast1("申请还款提交成功！");
//                            onlinePay.setEnabled(true);
//                            closeActivity();
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };

    @JavascriptInterface
    public void applyProtocol() {
        Intent contractIntent = new Intent(RepayVerifyActivity.this, DialogContractActivity.class);
        contractIntent.putExtra("url", "/webview/repayApplyProtocol?loanId=" + repay.getLoanId() + "&userId=" + Constants.LOGIN_USER.getId() + "&token=" + Constants.LOGIN_USER.getToken());
        contractIntent.putExtra("title", "米米贷借款协议");
        startActivity(contractIntent);
    }
    private void closeActivity(){
        Intent intent=new Intent(RepayVerifyActivity.this,RepayPayScuessfulActivity.class);
        startActivity(intent);
        RepayVerifyActivity.this.finish();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case LOCKINNG:
                    Third response = (Third) msg.obj;
                    if (response!=null&&response.getCode().equals("0")){
                        RepayVerifyActivity.this.finish();
                    }else if (response.getCode().equals("9")){
                        Intent intent = new Intent(RepayVerifyActivity.this,
                                WorthPurseUtil.getZhiddActivity().getClass());
                        intent.putExtra("login_state",response.getCode());
                        startActivity(intent);
                        showShortToast1("您的账号在其他设备登录,请重新登录");
                        finish();
                    }
                    break;
                case PREPAY:
                    GenerateOrders generateOrders = (GenerateOrders) msg.obj;
                    if (generateOrders!=null){
                        if (generateOrders.getCode().equals("0")){
                            if (generateOrders.getData()!=null){

                                //应还款
                                total_fee = generateOrders.getData().getTotal_fee();
                                //当前期数
                                term = generateOrders.getData().getTerm();
                                //实际金额
                                cash_fee = generateOrders.getData().getCash_fee();
                                String prepay_id = generateOrders.getData().getPrepay_id();
                                bundle_pay = new Bundle();
                                bundle_pay.putString("totalfee",total_fee);
                                bundle_pay.putString("term",term);
                                bundle_pay.putString("cash_fee",cash_fee);
                                bundle_pay.putString("prepay_id",prepay_id);
                                //支付宝
                                if (isMobile_spExist()){
                                    Intent intent = new Intent(RepayVerifyActivity.this, PayActivity.class);
                                    intent.putExtra("zhifubao_pay",bundle_pay);
                                    startActivity(intent);
                                    prepayDialog.dismiss();
                                }else{
                                    prepayDialog.dismiss();
                                }
                            }

                        }else if (generateOrders.getCode().equals("1")){
                            showShortToast1("系统繁忙，请您5分钟后重试！");
                        }else if (generateOrders.getCode().equals("9")){
                            Intent intent = new Intent(RepayVerifyActivity.this,
                                    WorthPurseUtil.getZhiddActivity().getClass());
                            startActivity(intent);
                            showShortToast1("您的账号在其他设备登录,请重新登录");
                            finish();
                        }
                    }else {
                        showShortToast1(generateOrders.getMsg());
                    }
                    break;
                case PAYMENT:
                    PayOrderList payOrderList = (PayOrderList) msg.obj;
                    if (payOrderList!=null){
                        if (payOrderList.getCode().equals("0")){
                            Log.i("创建订单成功.",payOrderList.getMsg());
                            showShortToast1(payOrderList.getMsg());
                            PayOrderList.DataBean data = payOrderList.getData();
                            if (data!=null){
                                busi_partner = data.getBusi_partner();
                                no_order = data.getNo_order();
                                dt_order = data.getDt_order();
                                name_goods = data.getName_goods();
                                sign_type = data.getSign_type();
                                notify_url = data.getNotify_url();
                                valid_order = data.getValid_order();
                                shareing_data = data.getShareing_data();
                                money_order = data.getMoney_order();
                                id_no = data.getId_no();
                                oid_partner = data.getOid_partner();
                                String dt_order = data.getDt_order();
                                acct_name = data.getAcct_name();
                                busi_partner = data.getBusi_partner();
                                no_agree = data.getNo_agree();
                                user_id = data.getUser_id();
                                sign1 = data.getSign();
                                info_order = data.getInfo_order();
                                card_no = data.getCard_no();
                                PayOrderList.DataBean.RiskItem riskItem = data.getRiskItem();
                                if (riskItem!=null){
                                    user_info_bind_phone = riskItem.getUser_info_bind_phone();
                                    user_info_dt_register = riskItem.getUser_info_dt_register();
                                    user_info_full_name = riskItem.getUser_info_full_name();
                                    user_info_id_no = riskItem.getUser_info_id_no();
                                    user_info_identify_state = riskItem.getUser_info_identify_state();
                                    user_info_identify_type = riskItem.getUser_info_identify_type();
                                    user_info_mercht_userlogin = riskItem.getUser_info_mercht_userlogin();
                                    user_info_mercht_userno = riskItem.getUser_info_mercht_userno();
                                }

                                lianlianPay();
                            }

                        }else if (payOrderList.getCode().equals("9")){
                            Intent intent = new Intent(RepayVerifyActivity.this,
                                WorthPurseUtil.getZhiddActivity().getClass());
                            startActivity(intent);
                            showShortToast1("您的账号在其他设备登录,请重新登录");
                            finish();
                        }else if (payOrderList.getCode().equals("1")){
                            showShortToast1(payOrderList.getMsg());
                        }else if (payOrderList.getCode().equals("4")){
                            showShortToast1(payOrderList.getMsg());
                        }
                    }
                    break;
            }

        }
    };
}
